<template>
  <view class="electricify-record-container">
    <!-- 合并后的筛选和记录区域 -->
    <!-- 日期选择器 -->
    <view class="date-selector">
    <view class="date-tabs">
        <view 
        v-for="(item, index) in dateTypeOptions" 
        :key="index"
        :class="['tab', dateType === item.value ? 'active' : '']"
        @click="handleTypeChange(item.value)"
        >
        {{ item.label === '按天' ? '日' : item.label === '按月' ? '月' : '年' }}
        </view>
    </view>
    
    <view class="date-picker">
        <view class="date-display">
        <view class="arrow-btn" @click="changeDateByStep(-1)">
            <u-icon name="arrow-left" size="20"></u-icon>
        </view>
        
        <text>{{ formatDisplayDate() }}</text>
        
        <view class="arrow-btn" @click="changeDateByStep(1)" v-if="!isCurrentDate()">
            <u-icon name="arrow-right" size="20"></u-icon>
        </view>
        <view class="arrow-btn-disabled" v-else>
            <u-icon name="arrow-right" size="20" color="#ccc"></u-icon>
        </view>
        </view>
    </view>
    </view>
    <view class="content-section">
      <!-- 记录列表区域 -->
      <view class="record-list-title">用电记录</view>
      
      <view v-if="recordList.length === 0" class="empty-data">
        <u-empty mode="data" text="暂无用电记录"></u-empty>
      </view>
      
      <view v-else class="record-list">
        <view class="record-header">
          <text class="header-item">{{ getTimeLabel() }}</text>
          <text class="header-item">用电量(度)</text>
        </view>
        
        <view 
          v-for="(item, index) in recordList" 
          :key="index"
          class="record-item"
        >
          <text class="item-time">{{ item.groupDate }}</text>
          <text class="item-usage">{{ item.kwh }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { roomElectricityRecord } from '@/api/room/index';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      // 筛选参数
      dateType: 'day', // 默认按天统计
      currentDate: dayjs(), // 当前选择的日期对象
      startDate: '',
      endDate: '',
      roomId: '',
      
      // 列表数据
      recordList: [],
      
      // 统计类型选项
      dateTypeOptions: [
        { label: '按年', value: 'year' },
        { label: '按月', value: 'month' },
        { label: '按天', value: 'day' },
      ]
    };
  },
  
  onLoad(options) {
    if (options.roomId) {
      this.roomId = options.roomId;
    } else {
        uni.showToast({
            title: '请先选择房间',
            icon: 'none'
        });
        return
    }
    
    // 初始化日期为当前日期
    this.currentDate = dayjs();
    
    // 设置日期范围并获取数据
    this.setDateRange();
    this.fetchRecords();
  },
  
  methods: {
    // 切换统计类型
    handleTypeChange(type) {
      this.dateType = type;
      this.currentDate = dayjs(); // 重置为当前日期
      this.setDateRange();
      this.recordList = [];
      this.fetchRecords();
    },
    
    // 格式化显示日期
    formatDisplayDate() {
      const formatMap = {
        day: 'YYYY-MM-DD',
        month: 'YYYY-MM',
        year: 'YYYY'
      };
      return this.currentDate.format(formatMap[this.dateType]);
    },
    
    // 检查是否为当前日期（不能超过当前年/月/日）
    isCurrentDate() {
      const now = dayjs();
      
      switch (this.dateType) {
        case 'year':
          return this.currentDate.year() >= now.year();
        case 'month':
          return this.currentDate.year() >= now.year() && 
                 this.currentDate.month() >= now.month();
        case 'day':
          return this.currentDate.year() >= now.year() && 
                 this.currentDate.month() >= now.month() && 
                 this.currentDate.date() >= now.date();
        default:
          return false;
      }
    },
    
    // 根据步长改变日期
    changeDateByStep(step) {
      // 如果是向后一步且已经是当前日期，则不执行
      if (step > 0 && this.isCurrentDate()) {
        return;
      }
      
      const unitMap = {
        day: 'day',
        month: 'month',
        year: 'year'
      };
      
      this.currentDate = this.currentDate.add(step, unitMap[this.dateType]);
      
      // 确保不超过当前日期
      const now = dayjs();
      if (this.dateType === 'year' && this.currentDate.year() > now.year()) {
        this.currentDate = now;
      } else if (this.dateType === 'month' && 
                (this.currentDate.year() > now.year() || 
                (this.currentDate.year() === now.year() && this.currentDate.month() > now.month()))) {
        this.currentDate = now;
      } else if (this.dateType === 'day' && this.currentDate.isAfter(now, 'day')) {
        this.currentDate = now;
      }
      
      this.setDateRange();
      this.fetchRecords();
    },
    
    // 设置日期范围
    setDateRange() {
      const current = this.currentDate;
      
      switch (this.dateType) {
        case 'year':
          this.startDate = current.startOf('year').format('YYYY-MM-DD');
          this.endDate = current.endOf('year').format('YYYY-MM-DD');
          break;
        case 'month':
          this.startDate = current.startOf('month').format('YYYY-MM-DD');
          this.endDate = current.endOf('month').format('YYYY-MM-DD');
          break;
        case 'day':
          this.startDate = current.format('YYYY-MM-DD');
          this.endDate = current.format('YYYY-MM-DD');
          break;
        default:
          break;
      }
    },
    
    // 获取记录列表
    async fetchRecords() {
      if (!this.roomId) {
        uni.showToast({
          title: '请先选择房间',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const params = {
          dateType: this.dateType,
          startDate: this.startDate,
          endDate: this.endDate,
          roomId: this.roomId
        };
        
        const res = await roomElectricityRecord(params);
        
        if (res.code === 200) {
          this.recordList = res.data || [];
        } else {
          uni.showToast({
            title: res.message || '获取数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取用电记录失败', error);
        uni.showToast({
          title: '获取数据失败，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 根据统计类型获取时间标签
    getTimeLabel() {
      const typeMap = {
        day: '日期',
        month: '月份',
        year: '年份'
      };
      return typeMap[this.dateType] || '时间';
    }
  }
};
</script>

<style lang="scss" scoped>
.electricify-record-container {
//   padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.date-selector {
    margin-bottom: 20rpx;
    
    .date-tabs {
      display: flex;
      border-bottom: 1px solid #eee;
      margin-bottom: 20rpx;
      
      .tab {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #666;
        position: relative;
        transition: all 0.3s;
        
        &.active {
          color: #2979ff;
          font-weight: 500;
          
          &::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 4rpx;
            background-color: #2979ff;
            border-radius: 2rpx;
          }
        }
      }
    }
    
    .date-picker {
      padding: 10rpx 0;
      
      .date-display {
        display: flex;
        align-items: center;
        justify-content: center;
        
        text {
          font-size: 32rpx;
          color: #333;
          margin: 0 10rpx;
        }
        
        .arrow-btn, .arrow-btn-disabled {
          padding: 10rpx;
        }
      }
    }
  }

.content-section {
  
  .record-list-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    padding: 0 20rpx;
  }
  
  .empty-data {
    padding: 60rpx 0;
  }
  
  .record-list {
    background-color: #fff;
    padding: 20rpx;
    .record-header {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1px solid #eee;
      font-size: 28rpx;
      font-weight: 500;
      color: #666;
      
      .header-item {
        flex: 1;
        text-align: center;
      }
    }
    
    .record-item {
      display: flex;
      padding: 30rpx 0;
      border-bottom: 1px solid #f5f5f5;
      font-size: 28rpx;
      color: #333;
      
      text {
        flex: 1;
        text-align: center;
      }
      
      .item-time {
        color: #333;
      }
      
      .item-usage {
        color: #2979ff;
        font-weight: 500;
      }
    }
  }
}
</style>
